package com.itheima.api.user;


import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.constant.HttpStatus;
import com.itheima.exception.UserException;
import com.itheima.mapper.user.UmsAdminMapper;
import com.itheima.vo.domain.TableDataInfo;
import com.itheima.vo.dto.AdminRoleDto;
import com.itheima.vo.pojo.UmsAdmin;
import com.itheima.vo.pojo.UmsAdminLoginLog;
import com.itheima.vo.pojo.UmsAdminRoleRelation;
import com.itheima.vo.pojo.UmsRole;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 用户登录业务层实现
 */
@DubboService
public class UmsAdminServiceImpl extends ServiceImpl<UmsAdminMapper, UmsAdmin> implements UmsAdminService {

    //订阅用户角色关系服务
    @DubboReference
    private UmsAdminRoleRelationService adminRoleRelationService;

    @DubboReference
    private UmsRoleService roleService;

    @DubboReference
    private UmsAdminLoginLogService loginLogService;


    /**
     * 校验登录是否成功并返回token的功能
     * @param umsAdmin 登录信息
     * @return  token字符串
     * 21232f297a57a5a743894a0e4a801fc3 管理员账号admin密码
     */
    @Transactional
    @Override
    public Map<String,Object> adminLogin(UmsAdmin umsAdmin,UmsAdminLoginLog loginLog) {
        String username = umsAdmin.getUsername();
        //判断该账号是否存在
        LambdaQueryWrapper<UmsAdmin> lqw=new LambdaQueryWrapper<>();
        lqw.eq(UmsAdmin::getUsername,username);
        UmsAdmin admin = this.getOne(lqw);
        if(admin==null) throw new UserException(HttpStatus.UNAUTHORIZED,"用户不存在");
        //账号存在,校验密码
        if(!admin.getPassword().equals(DigestUtils.md5DigestAsHex(umsAdmin.getPassword().getBytes())))
            throw new UserException(HttpStatus.UNAUTHORIZED,"密码错误");
        if(admin.getStatus().equals(0L)) throw new UserException(HttpStatus.UNAUTHORIZED,"该账号已被禁用");
        //密码正确,存储登录记录
        loginLog.setAdminId(admin.getId());
        loginLogService.save(loginLog);
        //将当前登录用户存储到map中
        Map<String,Object> map=new HashMap<>();
        map.put("user",admin);
        map.put("tokenHead","Bearer ");
        return map;
    }



    /**
     * 用户注册功能
     * @param umsAdmin 注册信息
     * @return 用户信息
     */
    @Override
    public UmsAdmin register(UmsAdmin umsAdmin) {
        String username = umsAdmin.getUsername();
        if(StringUtils.isEmpty(username)) throw new UserException(HttpStatus.ERROR,"用户名不能为空");
        //判断当前用户名在是否已存在
        LambdaQueryWrapper<UmsAdmin> lqw=new LambdaQueryWrapper<>();
        lqw.eq(UmsAdmin::getUsername,username);
        UmsAdmin one = this.getOne(lqw);
        if(one != null) throw new UserException(HttpStatus.ERROR,"该用户名已存在");
        //用户名不存在,进行注册
        umsAdmin.setCreateTime(LocalDateTime.now());
        umsAdmin.setStatus(1L);
        //对密码进行MD5加密
        umsAdmin.setPassword(DigestUtils.md5DigestAsHex(umsAdmin.getPassword().getBytes()));
        this.save(umsAdmin);
        return umsAdmin;
    }

    /**
     * 查询用户列表
     * @param keyword  模糊查询条件:用户名/昵称
     * @param pageNum  当前页码
     * @param pageSize  当前页条目数
     * @return  查询结果
     */
    @Override
    public TableDataInfo getList(String keyword, Integer pageNum, Integer pageSize) {
        Page<UmsAdmin> page=new Page<>(pageNum,pageSize);
        LambdaQueryWrapper<UmsAdmin> lqw=new LambdaQueryWrapper<>();
        lqw.like(StringUtils.isNotEmpty(keyword),UmsAdmin::getUsername,keyword).or()
                .like(StringUtils.isNotEmpty(keyword),UmsAdmin::getNickName,keyword);
        page=this.page(page,lqw);
        //将查询的数据封装到分页查询对象中
        return new TableDataInfo(page.getRecords(),pageNum,pageSize,page.getTotal(),page.getPages());
    }


    /**
     * 修改用户密码
     * @param map 用户名,新旧密码
     */
    @Override
    public void updatePassword(Map<String, String> map) {
        String newPassword = map.get("newPassword");
        String oldPassword = map.get("oldPassword");
        String username = map.get("username");
        //查询用户是否存在
        LambdaQueryWrapper<UmsAdmin> lqw=new LambdaQueryWrapper<>();
        lqw.eq(StringUtils.isNotEmpty(username),UmsAdmin::getUsername,username);
        UmsAdmin admin = this.getOne(lqw);
        if(admin==null) throw new UserException(HttpStatus.ERROR,"该用户不存在");
        String oldPwd = DigestUtils.md5DigestAsHex(oldPassword.getBytes());
        //当密码正确时进行修改操作
        if(admin.getPassword().equals(oldPwd)){
            //将新密码进行md5加密后存储
            admin.setPassword(DigestUtils.md5DigestAsHex(newPassword.getBytes()));
            this.updateById(admin);
            return;
        }
        throw new UserException(HttpStatus.ERROR,"密码错误");
    }


    /**
     * 给用户分配角色
     * @param dto 封装用户id和角色ids
     * 多次操作,添加事务
     */
    @Transactional
    @Override
    public void updateAdminRole(AdminRoleDto dto) {
        Long adminId = dto.getAdminId();
        List<Long> roleIds = dto.getRoleIds();
        //删除该用户的角色
        LambdaQueryWrapper<UmsAdminRoleRelation> lqw=new LambdaQueryWrapper<>();
        lqw.eq(UmsAdminRoleRelation::getAdminId,adminId);
        adminRoleRelationService.remove(lqw);
        //重新添加角色
        List<UmsAdminRoleRelation> relations=roleIds.stream().map(roleId->{
            UmsAdminRoleRelation relation=new UmsAdminRoleRelation();
            relation.setAdminId(adminId);
            relation.setRoleId(roleId);
            return relation;
        }).collect(Collectors.toList());
        adminRoleRelationService.saveBatch(relations);
    }

    /**
     * 获取指定用户的角色
     * @param adminId 用户id
     * @return  角色集合
     */
    @Override
    public List<UmsRole> getAdminRoles(Long adminId) {
        //查询获取角色id
        LambdaQueryWrapper<UmsAdminRoleRelation> lqw=new LambdaQueryWrapper<>();
        lqw.eq(UmsAdminRoleRelation::getAdminId,adminId);
        List<UmsAdminRoleRelation> umsAdminRoleRelations = adminRoleRelationService.list(lqw);
        List<Long> roleIds = CollUtil.getFieldValues(umsAdminRoleRelations, "roleId", Long.class);
        if(roleIds==null || roleIds.size()==0) return null;
        //查询获取角色集合并返回
        return roleService.listByIds(roleIds);
    }


    /**
     *获取当前登录用户信息
     * @param loginUser 当前登录用户
     * @return  用户角色,用户头像,用户菜单,用户名
     */
    @Override
    public Map<String, Object> getCurrentLoginAdmin(UmsAdmin loginUser) {
        Long adminId = loginUser.getId();
        //获取当前用户角色
        LambdaQueryWrapper<UmsAdminRoleRelation> adminRole=new LambdaQueryWrapper<>();
        adminRole.eq(UmsAdminRoleRelation::getAdminId,adminId);
        List<UmsAdminRoleRelation> umsAdminRoleRelations = adminRoleRelationService.list(adminRole);
        //获取角色id
        List<Long> roleIds = CollUtil.getFieldValues(umsAdminRoleRelations, "roleId", Long.class);
        List<UmsRole> roles = roleService.listByIds(roleIds);
        //排除被禁用的角色
        roles=roles.stream().map(role -> {
            if(role.getStatus().equals(0)) return null;
            return role;
        }).collect(Collectors.toList());
        roles.removeAll(Collections.singleton(null));
        roleIds = CollUtil.getFieldValues(roles,"id", Long.class);
        //获取用户的角色名
        List<String> roleNames = CollUtil.getFieldValues(roles, "name", String.class);
        //获取用户菜单
        Map<String,Object> map=roleService.getCurrentLoginMenus(roleIds);
        map.put("username",loginUser.getUsername());
        map.put("icon",loginUser.getIcon());
        map.put("roles",roleNames);
        return map;
    }
}
